<template>
  <el-dialog
    v-model="dialogVisible"
    title="字符选择器"
    :before-close="closeDialog"
    width="600px"
  >
    <CharacterSelector
        ref ="characterSelectorRef"
        @character-selected="onCharacterSelected"
        v-bind="$props"
    />
    <template #footer>
        <span class="dialog-footer">
        <el-button type="primary" @click="confirmDialog">确认</el-button>
        <el-button @click="closeDialog">取消</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import CharacterSelector from '@/components/characterSelector/character-selector.vue'

const props = defineProps({
  dialogName: String,
  selected: String,
  onConfirm: Function,
  onCancel: Function,
})
const emit = defineEmits(['character-selected','confirm', 'cancel'])
const characterSelectorRef = ref(null)
// Data
const dialogVisible = ref(true)

// 确认操作
const confirmDialog = () => {
  // 获取选中的字符
  let selectedChar = ''
  if (characterSelectorRef.value) {
    if (typeof characterSelectorRef.value.getSelectedChars === 'function') {
      selectedChar = characterSelectorRef.value.getSelectedChars()
    }
  }
  
  // 调用传递过来的 onConfirm 回调
  if (props.onConfirm && typeof props.onConfirm === 'function') {
    try {
      props.onConfirm(selectedChar)
    } catch (error) {
      console.error('onConfirm 回调执行出错:', error)
    }
  } else {
    console.log('onConfirm 回调不存在或不是函数')
  }
  
  // 触发内部事件
  emit('confirm', selectedChar)
  
  // 关闭对话框
  dialogVisible.value = false
}

// 取消操作
const closeDialog = () => {
  // 调用传递过来的 onCancel 回调
  if (props.onCancel && typeof props.onCancel === 'function') {
    props.onCancel()
  }
  // 触发内部事件
  emit('cancel')
  // 关闭对话框
  dialogVisible.value = false
}

const onCharacterSelected = (char) => {
  emit('character-selected', char)
}

// Lifecycle
onMounted(() => {
  dialogVisible.value = true  
})

onBeforeUnmount(() => {
  
})
</script>